﻿using Mes.原料管理;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http.Headers;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Mes.车间机床.Model;
using System.IO;

namespace Mes.车间机床
{
    public partial class UpdateMachineFrom : Form
    {
        private string _id;
        private string _currentImagePath; // 保存当前图片路径

        public UpdateMachineFrom(string id)
        {
            InitializeComponent();
            _id = id;
            LoadMachineData();
        }

        private async void LoadMachineData()
        {
            try
            {
                // 添加调试信息
                Console.WriteLine($"当前工作目录: {Application.StartupPath}");
                Console.WriteLine($"当前目录: {Directory.GetCurrentDirectory()}");
                
                using (HttpClient client = new HttpClient())
                {
                    client.DefaultRequestHeaders.Authorization =
                       new AuthenticationHeaderValue("Bearer", login.CurrentToken);
                    client.BaseAddress = new Uri("https://localhost:7084/");
                    HttpResponseMessage response = await client.GetAsync($"api/Machine/GetMachinevalue?Id={_id}");

                    if (response.IsSuccessStatusCode)
                    {
                        string json = await response.Content.ReadAsStringAsync();
                        if (string.IsNullOrEmpty(json))
                        {
                            MessageBox.Show("API 返回的数据为空！");
                            return;
                        }
                        var apiResponse = JsonConvert.DeserializeObject<MachineRepositoryss>(json);
                        // 检查 material 是否为
                        if (apiResponse?.code != 200 || apiResponse.data == null || apiResponse.data.Count == 0)
                        {
                            MessageBox.Show("API 返回的数据无效！");
                            return;
                        }
                        var workshop = apiResponse.data[0];
                        
                        // 显示图片信息用于调试
                        Console.WriteLine($"数据库中的图片字段值: {workshop.img}");
                        
                        textUpdateMachineCode.Text = workshop.machineToolCode?.ToString() ?? "";
                        textUpdateMachineName.Text = workshop.machineToolName?.ToString() ?? "";
                        comUpdateMachineType.Text = workshop.machineToolType?.ToString() ?? "";
                        comUpdateMachineState.Text = workshop.machineToolStates?.ToString() ?? "";
                        comUpdateshengcai.Text = workshop.productionLines?.ToString() ?? "";
                        
                        // 处理日期字段
                        if (workshop.procurementDate.HasValue)
                        {
                            UpdateskinDatecaigouDate.text = workshop.procurementDate.Value.ToString("yyyy-MM-dd");
                        }
                        
                        textUpdateAdd.Text = workshop.addPeople?.ToString() ?? "";
                        
                        if (workshop.addDate.HasValue)
                        {
                            UpdateskinDateAddDate.text = workshop.addDate.Value.ToString("yyyy-MM-dd");
                        }
                        
                        // 处理图片字段
                        if (!string.IsNullOrEmpty(workshop.img))
                        {
                            _currentImagePath = workshop.img;
                            try
                            {
                                // 构建完整的图片路径
                                string imagePath = "";
                                string[] possiblePaths = {
                                    Path.Combine(Application.StartupPath, "Images", workshop.img),
                                    Path.Combine(Application.StartupPath, "Uploads", workshop.img),
                                    Path.Combine(Application.StartupPath, "wwwroot", "images", workshop.img),
                                    Path.Combine(Application.StartupPath, "Content", "images", workshop.img),
                                    Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "MES_Images", workshop.img),
                                    workshop.img // 原始值作为备选
                                };
                                
                                // 如果img包含完整路径，直接使用
                                if (workshop.img.Contains("\\") || workshop.img.Contains("/"))
                                {
                                    imagePath = workshop.img;
                                }
                                else
                                {
                                    // 如果只是文件名，构建完整路径
                                    // 尝试多个可能的路径
                                    foreach (string path in possiblePaths)
                                    {
                                        if (File.Exists(path))
                                        {
                                            imagePath = path;
                                            break;
                                        }
                                    }
                                }
                                
                                if (!string.IsNullOrEmpty(imagePath) && File.Exists(imagePath))
                                {
                                    UpdateskinPictureBox1.Image = Image.FromFile(imagePath);
                                    Console.WriteLine($"图片加载成功：{imagePath}");
                                }
                                else
                                {
                                    // 如果文件不存在，显示默认图片或清空
                                    UpdateskinPictureBox1.Image = null;
                                    Console.WriteLine($"图片文件不存在，尝试的路径：{string.Join(", ", possiblePaths)}");
                                    MessageBox.Show($"图片文件不存在：{workshop.img}\n请检查图片文件是否在正确位置。");
                                }
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show($"加载图片失败：{ex.Message}\n图片路径：{workshop.img}");
                                UpdateskinPictureBox1.Image = null;
                                Console.WriteLine($"图片加载异常：{ex.Message}");
                            }
                        }
                        else
                        {
                            UpdateskinPictureBox1.Image = null;
                            _currentImagePath = "";
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载数据失败：{ex.Message}");
            }
        }

        private async void btnUpdate_Click(object sender, EventArgs e)
        {
            try
            {
                // 表单验证
                if (string.IsNullOrWhiteSpace(textUpdateMachineName.Text))
                {
                    MessageBox.Show("请填写设备名称");
                    return;
                }
                if (string.IsNullOrWhiteSpace(comUpdateMachineType.Text))
                {
                    MessageBox.Show("请选择设备类型");
                    return;
                }
                if (string.IsNullOrWhiteSpace(comUpdateMachineState.Text))
                {
                    MessageBox.Show("请选择设备状态");
                    return;
                }
                if (string.IsNullOrWhiteSpace(comUpdateshengcai.Text))
                {
                    MessageBox.Show("请选择生产线");
                    return;
                }
                if (string.IsNullOrWhiteSpace(textUpdateAdd.Text))
                {
                    MessageBox.Show("请填写添加人");
                    return;
                }

                var material = new
                {
                    id = _id, // 使用小写的id字段
                    machineToolCode = textUpdateMachineCode.Text,
                    machineToolName = textUpdateMachineName.Text,
                    machineToolType = comUpdateMachineType.Text,
                    machineToolStates = comUpdateMachineState.Text,
                    productionLines = comUpdateshengcai.Text,
                    procurementDate = UpdateskinDatecaigouDate.text,
                    addPeople = textUpdateAdd.Text,
                    addDate = UpdateskinDateAddDate.text,
                    img = _currentImagePath, // 使用保存的图片路径
                };

                string json = JsonConvert.SerializeObject(material);
                var content = new StringContent(json, Encoding.UTF8, "application/json");

                using (HttpClient client = new HttpClient())
                {
                    client.DefaultRequestHeaders.Authorization =
                       new AuthenticationHeaderValue("Bearer", login.CurrentToken);
                    client.BaseAddress = new Uri("https://localhost:7084/");
                    HttpResponseMessage response = await client.PostAsync(
                        "api/Machine/UpdateMachine",
                        content);

                    if (response.IsSuccessStatusCode)
                    {
                        MessageBox.Show("修改成功！");
                        this.DialogResult = DialogResult.OK; // 通知主窗体刷新数据
                        this.Close();
                    }
                    else
                    {
                        string error = await response.Content.ReadAsStringAsync();
                        MessageBox.Show($"修改失败：{response.StatusCode}\n{error}");
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存失败：{ex.Message}");
            }
        }

        // 添加图片选择功能
        private async void UpdateskinPictureBox1_Click(object sender, EventArgs e)
        {
            using (OpenFileDialog openFileDialog = new OpenFileDialog())
            {
                openFileDialog.Filter = "图片文件|*.jpg;*.jpeg;*.png;*.bmp;*.gif|所有文件|*.*";
                openFileDialog.Title = "选择图片";
                
                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    try
                    {
                        // 显示选中的图片
                        UpdateskinPictureBox1.Image = Image.FromFile(openFileDialog.FileName);
                        
                        // 上传图片到后端
                        using (HttpClient client = new HttpClient())
                        {
                            string apiUrl = "http://10.223.8.11:8083/api/File/UploadFile";
                            byte[] imageBytes = File.ReadAllBytes(openFileDialog.FileName);
                            var content = new MultipartFormDataContent();
                            content.Add(new ByteArrayContent(imageBytes), "file", openFileDialog.SafeFileName);

                            HttpResponseMessage response = await client.PostAsync(apiUrl, content);

                            if (response.IsSuccessStatusCode)
                            {
                                string fullPath = (await response.Content.ReadAsStringAsync())?.Trim().Trim('"');
                                
                                if (!string.IsNullOrEmpty(fullPath))
                                {
                                    // 生成图片标识符
                                    string timestamp = DateTime.Now.ToString("yyyyMMddHHmmss");
                                    string originalFileName = openFileDialog.SafeFileName;
                                    string extension = Path.GetExtension(originalFileName);
                                    string nameWithoutExt = Path.GetFileNameWithoutExtension(originalFileName);
                                    
                                    if (nameWithoutExt.Length > 30)
                                    {
                                        nameWithoutExt = nameWithoutExt.Substring(0, 30);
                                    }
                                    
                                    string newImagePath = $"{timestamp}_{nameWithoutExt}{extension}";
                                    
                                    if (newImagePath.Length > 50)
                                    {
                                        newImagePath = newImagePath.Substring(0, 50);
                                    }
                                    
                                    // 保存到本地Images目录
                                    string imagesDirectory = Path.Combine(Application.StartupPath, "Images");
                                    if (!Directory.Exists(imagesDirectory))
                                    {
                                        Directory.CreateDirectory(imagesDirectory);
                                    }
                                    
                                    string targetPath = Path.Combine(imagesDirectory, newImagePath);
                                    File.Copy(openFileDialog.FileName, targetPath, true);
                                    
                                    _currentImagePath = newImagePath;
                                    Console.WriteLine($"图片上传成功！\n存储标识: {newImagePath}\n本地路径: {targetPath}");
                                    MessageBox.Show($"图片上传成功！\n存储标识: {newImagePath}");
                                }
                            }
                            else
                            {
                                MessageBox.Show($"图片上传失败：{response.StatusCode}");
                                // 如果上传失败，清空图片显示
                                UpdateskinPictureBox1.Image = null;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show($"加载图片失败：{ex.Message}");
                        UpdateskinPictureBox1.Image = null;
                        Console.WriteLine($"图片处理异常：{ex.Message}");
                    }
                }
            }
        }
    }
    
}
